package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void remove(Long id) {

        // 根据id查询当前分类的菜品数量
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        Integer dishCount = dishMapper.selectCount(dishLambdaQueryWrapper);

        // 判断是否有菜品
        if (dishCount > 0) {
            throw new CustomException("当前分类下有菜品数据，不能删除！");
        }

        // 根据id查询当前分类的套餐数量
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        Integer setmealCount = setmealMapper.selectCount(setmealLambdaQueryWrapper);

        // 判断是否有套餐
        if (setmealCount > 0) {
            throw new CustomException("当前分类下有套餐数据，不能删除！");
        }

        // 执行删除语句
        this.removeById(id);

    }
}
